//
//  Settings.m
//  网易新闻
//
//  Created by dllo on 15/10/12.
//  Copyright (c) 2015年 Lx. All rights reserved.
//

#import "Settings.h"
#import <sqlite3.h>
@interface Settings()
@property(nonatomic, retain)NSString *setPath;
@property(nonatomic, retain)NSMutableDictionary *setDic;
@end
@implementation Settings
static sqlite3 *db;
//初始化
- (instancetype)init{
    self = [super init];
    if (self) {
        self.isNight = NO;
//        self.setPath = [[NSBundle mainBundle]pathForResource:@"Settings" ofType:@"plist"];
//        self.setDic = [[NSDictionary alloc]initWithContentsOfFile:self.setPath].mutableCopy;
        //获取document路径
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        self.setPath = [documentsDirectory stringByAppendingPathComponent:@"Settings.plist"];
        
        //判断文件是否存在
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if(![fileManager fileExistsAtPath:self.setPath])//如果不存在
        {
            //获取程序包中相应文件的路径
            NSString *dataPath = [[NSBundle mainBundle]pathForResource:@"Settings" ofType:@"plist"];
            //拷贝
            [fileManager copyItemAtPath:dataPath toPath:self.setPath error:nil];
        }
        
        self.setDic = [[NSDictionary alloc]initWithContentsOfFile:self.setPath].mutableCopy;
    }
    return self;
}
//创建单例
+ (instancetype)shareSettings{
    static Settings *setting = nil;
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        setting = [[Settings alloc]init];
    });
    return setting;
}

//引导页的检测
- (BOOL)isFirst{
    BOOL isFirst = [self.setDic objectForKey:@"Is_first"];
    return isFirst;
}
- (void)changeFirst{
    [self.setDic setValue:(Boolean)NO forKey:@"Is_first"];
    [self.setDic writeToFile:self.setPath atomically:YES];
}

//收藏
- (NSArray *)addressArr{
    NSArray *address = [self.setDic objectForKey:@"address"];
    return address;
}
- (NSArray *)collectionsArr{
    NSArray *address = [self.setDic objectForKey:@"collections"];
    return address;
}
- (BOOL)checkDocid:(NSString *)docid{
    for (NSDictionary *dic in [self.setDic objectForKey:@"collections"]) {
        if ([[dic objectForKey:@"docid"]isEqualToString:docid]) {
            return YES;
        }
    }
    return NO;
}
- (void)changeCollectionArr:(NSMutableArray *)muArr{
    NSArray *arr = [[NSArray alloc]initWithArray:muArr];
    [self.setDic setValue:arr forKey:@"collections"];
    [self.setDic writeToFile:self.setPath atomically:YES];
    [arr release];
}

//夜间模式
- (UIColor *)color:(colorStyle)colorstyle{
    switch (colorstyle) {
        case GrayToBlack:
            if (self.isNight) {
                return [UIColor blackColor];
            }else{
                return [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
            }
            break;
        case WhiteToGray:
            if (self.isNight) {
                return [UIColor colorWithRed:0.3 green:0.3 blue:0.3 alpha:1];
            }else{
                return [UIColor whiteColor];
            }
            break;
        case WhiteToLightGray:
            if (self.isNight) {
                return [UIColor grayColor];
            }else{
                return [UIColor whiteColor];
            }
            break;
        case BlackToWhite:
            if (self.isNight) {
                return [UIColor whiteColor];
            }else{
                return [UIColor blackColor];
            }
            break;
        default:
            return [UIColor blackColor];
            break;
    }
}

//缓存
- (BOOL)checkDB{
    BOOL openDB = NO;
    //数据库文件路径
    NSString *dbPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"cache.sqlite"];
//    NSLog(@"%@", dbPath);
    if (db != nil) {
        openDB = YES;
    }else{
        //数据库文件和数据库对象关联
        int result = sqlite3_open(dbPath.UTF8String, &db);
        if (SQLITE_OK == result) {
            openDB = YES;
        }
    }

    BOOL createTable = NO;
    //SQL语句
    NSString *table = @"CREATE TABLE IF NOT EXISTS results(titleID INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, data TEXT)";
    //对数据库操作
    int result = sqlite3_exec(db, table.UTF8String, nil, nil, nil);
    //判断
    if (SQLITE_OK == result) {
        createTable = YES;
    }
    
    if (openDB && createTable) {
        return YES;
    }else{
        return NO;
    }
}
- (BOOL)checkName:(NSString *)name{
    const unsigned char *check = 0;
    if ([self checkDB]) {
        NSString *selectSQL = [NSString stringWithFormat:@"SELECT * FROM results WHERE name = '%@'", name];
        sqlite3_stmt *stmt = nil;
        int result = sqlite3_prepare_v2(db, selectSQL.UTF8String, -1, &stmt, NULL);
        if (SQLITE_OK == result) {
            while (SQLITE_ROW == sqlite3_step(stmt)) {
                 check = sqlite3_column_text(stmt, 1);
            }
            sqlite3_finalize(stmt);
            if (check != 0) {
                return YES;
            }else{
                return NO;
            }
        }else{
            return NO;
        }
    }else{
        return NO;
    }
}
- (void)writeToDBWithDic:(NSDictionary *)dic WithName:(NSString *)name{
    if (![self checkName:name]) {
        //字典转字符串
        NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *data = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        //SQL
        NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO results(name, data) VALUES('%@', '%@')", name, data];
        int result = sqlite3_exec(db, insertSQL.UTF8String, nil, nil, nil);
        if (SQLITE_OK == result) {
//            NSLog(@"%@缓存成功", name);
        }else{
//            NSLog(@"%@缓存失败: %d", name, result);
        }
    }else{
        NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *data = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        //SQL
        NSString *insertSQL = [NSString stringWithFormat:@"UPDATE results SET data = '%@' WHERE name = '%@'", data, name];
        int result = sqlite3_exec(db, insertSQL.UTF8String, nil, nil, nil);
        if (SQLITE_OK == result) {
//            NSLog(@"%@更新成功", name);
        }else{
//            NSLog(@"%@更新失败: %d", name, result);
        }
    }
}
- (NSDictionary *)dicSelectFromDB:(NSString *)name{
    if ([self checkDB]) {
        NSDictionary *dic = [[NSDictionary alloc]init];
        //SQL
        NSString *selectSQL = [NSString stringWithFormat:@"SELECT * FROM results WHERE name = '%@'", name];
        //准备好的语句对象stmt 二进制,准备语句（prepared statement）对象一个代表一个简单SQL语句对象的实例
        sqlite3_stmt *stmt = nil;
        //编译SQL语句,不执行, 将sql文本转换成一个准备语句（prepared statement）对象，同时返回这个对象的指针给stmt
        int result = sqlite3_prepare_v2(db, selectSQL.UTF8String, -1, &stmt, NULL);
        //判断
        if (SQLITE_OK == result) {
            //逐行进行查询, 当sqlite3_step()返回值等于SQLITE_ROW说明还有数据
            while (SQLITE_ROW == sqlite3_step(stmt)) {
                //如果查询结果需要操作, 调用sqlite3_column函数簇对stmt列进行操作
                NSString *data = [NSString stringWithUTF8String:(const char*)sqlite3_column_text(stmt, 2)];//第三列
                //字符串转字典
                NSData *jsonData = [data dataUsingEncoding:NSUTF8StringEncoding];
                dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
            }
            //销毁stmt对象
            sqlite3_finalize(stmt);
            if ([dic isEqual:@{}]) {
                return nil;
            }else{
                return dic;
            }
        }else{
            sqlite3_finalize(stmt);
            return nil;
        }
    }
    return nil;
}
- (void)closeDB{
    sqlite3_close(db);
    db = nil;//否则第二次报错
}









- (void)dealloc{
    [_setPath release];
    [_setDic release];
    [super dealloc];
}

@end
